package com.example.musicplayer;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.animation.ObjectAnimator;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import java.lang.ref.WeakReference;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static SeekBar sb;                       //进度表
    private static TextView tv_progress, tv_total;   //文本框
    private ObjectAnimator animator;                 //动画
    private MusicService.MusicControl musicControl;  //绑定服务返回的服务代理对象
    public static MyHandler handler;                 //消息处理对象
    MyServiceConn conn;                              //绑定服务的连接对象
    Intent intent;                                   //意图对象
    private boolean isUnbind = false;                //记录服务是否被解绑

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        tv_progress = (TextView) findViewById(R.id.tv_progress);
        tv_total = (TextView) findViewById(R.id.tv_total);
        sb = (SeekBar) findViewById(R.id.sb);
        findViewById(R.id.btn_play).setOnClickListener(this);
        findViewById(R.id.btn_pause).setOnClickListener(this);
        findViewById(R.id.btn_continue_paly).setOnClickListener(this);
        findViewById(R.id.btn_exit).setOnClickListener(this);
        intent = new Intent(this, MusicService.class); //实例化意图对象
        conn = new MyServiceConn();                    //实例化服务连接对象
        bindService(intent, conn, BIND_AUTO_CREATE);   //绑定服务
        //为滑动条添加事件监听
        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override //滑动条改变时调用
            public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
                if (progress == seekBar.getMax()) {       //如果到最大值
                    animator.pause();                     //动画暂停
                }
            }

            @Override //滑动条开始滑动时调用
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override //滑动条停止滑动时调用
            public void onStopTrackingTouch(SeekBar seekBar) {
                //根据拖到的进度改变音乐播放进度
                int progress = seekBar.getProgress();    //获取进度条的位置
                musicControl.seekTo(progress);           //设置从进度条指定位置处播放
            }
        });
        ImageView iv_music = (ImageView) findViewById(R.id.iv_music);
        animator = ObjectAnimator.ofFloat(iv_music, "rotation", 0f, 360.0f);
        animator.setDuration(10000);          //图片每10秒旋转1圈
        animator.setInterpolator(new LinearInterpolator());
        animator.setRepeatCount(-1);
        musicControl = new MusicService().new MusicControl();
        handler= new MyHandler(this);            //实例化消息处理对象handler
    }

    static class MyHandler extends Handler {
        //解决Handler默认构造方法过时的问题，防止出现内存泄露
        WeakReference<MainActivity> mactivity;
        //构造函数，传来的是外部类的this
        public MyHandler(MainActivity activity){
            mactivity = new WeakReference<MainActivity>(activity);
        }
        //在主线程中处理从子线程发送过来的消息
        @Override
        public void handleMessage(@NonNull Message msg) {
            Bundle bundle = msg.getData();        //从msg中读取加载的数据bundle
            int duration = bundle.getInt("duration");    //从bundle中获取歌曲总时长
            int currentPosition = bundle.getInt("currentPosition");  //获取当前播放时长
            sb.setMax(duration);                  //设置进度条的总时长
            sb.setProgress(currentPosition);      //设置进度条的当前值
            Log.i("TAG", "handleMessage: " + duration + " " + currentPosition);
            //计算歌曲的总时长
            int minute = duration / 1000 / 60;  //分钟数
            int second = duration / 1000 % 60;  //秒数
            String strMinute = null;        //构造分钟字符串
            String strSecond = null;        //构造秒数字符串
            if (minute < 10) {              //如果分钟数小于10，则前面加“0”
                strMinute = "0" + minute;
            } else {
                strMinute = minute + "";
            }
            if (second < 10) {              //如果秒数小于10，则前面加“0”
                strSecond = "0" + second;
            } else {
                strSecond = second + "";
            }
            tv_total.setText(strMinute + ":" + strSecond);  //显示结果为xx:xx
            //计算歌曲当前播放时长
            minute = currentPosition / 1000 / 60;
            second = currentPosition / 1000 % 60;
            if (minute < 10) {
                strMinute = "0" + minute;
            } else {
                strMinute = minute + "";
            }
            if (second < 10) {
                strSecond = "0" + second;
            } else {
                strSecond = second + "";
            }
            tv_progress.setText(strMinute + ":" + strSecond); //显示结果为xx:xx
        }
    }

    class MyServiceConn implements ServiceConnection {          //创建用于绑定服务的类
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            musicControl=(MusicService.MusicControl) iBinder;   //实例化MusicService.MusicControl对象
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    }

    private void unbind(boolean isUnbind){
        if(!isUnbind){
            musicControl.pausePlay();   //停止播放
            unbindService(conn);        //解绑服务
            stopService(intent);        //停止服务
        }
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.btn_play:           //播放音乐按钮点击事件
                musicControl.play();      //播放音乐
                animator.start();         //播放动画
                break;
            case R.id.btn_pause:          //暂停按钮点击事件
                musicControl.pausePlay(); //暂停音乐播放
                animator.pause();         //暂停动画播放
                break;
            case R.id.btn_continue_paly:      //继续播放按钮点击事件
                musicControl.continuePlay();  //继续播放音乐
                animator.start();             //播放动画
                break;
            case R.id.btn_exit:               //退出按钮点击事件
                unbind(isUnbind);             //执行解绑服务的方法unbind()，解绑服务
                isUnbind=true;                //解绑后设置解绑标志变量isUnbind=true
                finish();                     //关闭音乐播放界面
                break;
        }
    }
}
